package shopping.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;
import shopping.dao.ProductDao;
import shopping.domain.Product;
import shopping.utils.RedisUtil;

import java.util.List;

public class ProductService {
    public List<Product> findNews() {
        Jedis connection = null;
        try {
            connection = RedisUtil.getConnection();
            String news = connection.get("news");
            if(news == null){
                //第一次去查询数据
                System.out.println("调用数据库查询最新商品");
                List<Product> products = new ProductDao().findNews();
                String s = new ObjectMapper().writeValueAsString(products);
                //存入缓存
                connection.set("news",s);
                //为可能会经常修改的数据设置一个过期时间,5分钟
                connection.expire("news",300);

                return products;
            }else{
                //缓存中存在该数据，直接返回
                List list = new ObjectMapper().readValue(news, List.class);
                return list;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            connection.close();
        }
    }

    public List<Product> findHots() {
        Jedis connection = null;
        try {
            connection = RedisUtil.getConnection();
            String hots = connection.get("hots");
            if(hots == null){
                System.out.println("调用数据库查询热门商品");
                List<Product> products = new ProductDao().findHots();

                String s = new ObjectMapper().writeValueAsString(products);
                connection.set("hots",s);
                connection.expire("hots",300);
                return products;
            }else{
                List list = new ObjectMapper().readValue(hots, List.class);
                return list;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            connection.close();
        }
    }

    public Product findById(String pid) {
        return new ProductDao().findById(pid);
    }

    public List<Product> findByPageWithCid(String cid, int pageNumber, int pageSize) {
        return new ProductDao().findByPageWithCid(cid,pageNumber,pageSize);
    }

    public int count(String cid) {
        return new ProductDao().count(cid);
    }

    public List<Product> findByPage(int pageNumber, int pageSize) {
        return new ProductDao().findByPage(pageNumber,pageSize);
    }

    public int count() {
        return new ProductDao().count();
    }

    public void save(Product product) {
        new ProductDao().save(product);
    }
}
